package com.lx.preferred.mall.authcenter.config;

import com.lx.preferred.mall.authcenter.enhancer.PreferredMallTokenEnhancer;
import com.lx.preferred.mall.authcenter.properties.JwtCAProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import javax.annotation.Resource;
import java.security.KeyPair;

/**
 * @author lX
 * @version JDK 8
 * @className JwtTokenStoreConfig (此处以class为例)
 * @date 2024/12/12
 * @description JWT存储配置
 */
@Configuration
@EnableConfigurationProperties(value = JwtCAProperties.class)
public class JwtTokenStoreConfig {


  @Resource
  private JwtCAProperties jwtCAProperties;

  @Bean
  public TokenStore jwtTokenStore(){
    return new JwtTokenStore(jwtAccessTokenConverter());
  }

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter(){
    JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
    //配置JWT使用的秘钥
    //accessTokenConverter.setSigningKey("123123");
    accessTokenConverter.setKeyPair(keyPair());
    return accessTokenConverter;
  }

  @Bean
  public KeyPair keyPair() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
      new ClassPathResource(jwtCAProperties.getKeyPairName()),
      jwtCAProperties.getKeyPairSecret().toCharArray());
    return keyStoreKeyFactory.getKeyPair(jwtCAProperties.getKeyPairAlias(),
      jwtCAProperties.getKeyPairStoreSecret().toCharArray());
  }

  @Bean
  public PreferredMallTokenEnhancer preferredMallTokenEnhancer() {
    return new PreferredMallTokenEnhancer();
  }
}
